import Vue from 'vue'
import Router from 'vue-router'
import Login from '../views/Login'
import Home from '../views/Home'
import Welcome from '../components/Welcome'
import Users from '../views/user/Users'
import Rights from '../views/power/Rights'
import Roles from '../views/power/Roles'
import Categories from '../views/goods/Categories'
import Params from '../views/goods/Params'
import List from '../views/goods/List'
import Add from '../views/goods/Add'
import Order from '../views/order/Order'
import Report from '../views/report/Report'


Vue.use(Router)
const routes=[
  {
    // 重定向
    path: '/',
    redirect:'/login'
  },
  {
    path:'/login',
    component:Login
  },
  {
    path:'/home',
    component:Home,
    redirect:'/welcome',
    children:[
      {
        path:'/welcome',
        component:Welcome
      },
      {
        path:'/users',
        component: Users
      },
      {
        path:'/rights',
        component:Rights
      },
      {
        path:'/roles',
        component:Roles
      },
      {
        path:'/categories',
        component:Categories
      },
      {
        path:'/params',
        component:Params
      },
      {
        path:'/goods',
        component:List
      },
      {
        path:'/goods/add',
        component:Add
      },
      {
        path:'/orders',
        component:Order
      },
      {
        path:'/reports',
        component:Report
      }
    ]
  }
]

const router = new Router({
  routes,
  mode:'history'
})
//挂载路由导航守卫,路由导航守卫控制访问权限，如果用户没有登录，但是直接通过url访问特定的页面，需要重新导航到登录页面
router.beforeEach((to,from,next)=>{
  //to将要访问的路径，from代表从那个路径跳转而来，next是一个函数，表示放行：1.next() 放行
  //                                                                  2.next('/login') 强制跳转
  //如果用户访问的登录页，直接放行
  if (to.path==='/login') return next()
  //获取token，从sessionStorage中获取
  const token=window.sessionStorage.getItem('token');
  //没有token，强制跳转到登录页
  if (!token) return next('/login');
  next();
})



export default router
